package main

import (
	"context"
	"fmt"
	"github.com/go-kit/kit/endpoint"
	"github.com/go-kit/kit/log"
	"github.com/go-kit/kit/sd"
	"github.com/go-kit/kit/sd/consul"
	"github.com/go-kit/kit/sd/lb"
	httptransport "github.com/go-kit/kit/transport/http"
	consulapi "github.com/hashicorp/consul/api"
	logging "github.com/sirupsen/logrus"
	"io"
	"net/url"
	"os"
	"time"
	"webdemo/src/go-kit-client/service"
)

const (
	consulAddress    = "127.0.0.1:8500"
	registrationName = "go-kit"
)

func main() {

	// 创建客户端
	config := consulapi.DefaultConfig()
	config.Address = consulAddress
	api_client, err := consulapi.NewClient(config)
	if err != nil {
		logging.Error("consul client error : ", err)
	}
	client := consul.NewClient(api_client)

	// 查询服务实例
	var logger log.Logger
	{
		logger = log.NewLogfmtLogger(os.Stdout)
	}
	tags := []string{"v1"}
	instancer := consul.NewInstancer(client, logger, registrationName, tags, true)

	f := func(service_url string) (endpoint.Endpoint, io.Closer, error) {
		URL, _ := url.Parse("http://" + service_url)
		return httptransport.NewClient("GET", URL, service.GetUserInfoRequestEncode, service.GetUserInfoResponseDecode).Endpoint(), nil, nil
	}
	endpointer := sd.NewEndpointer(instancer, f, logger)
	endpoints, err := endpointer.Endpoints()
	fmt.Println("server len is ", len(endpoints))
	//getUserInfoEndpoint := endpoints[0]
	// 轮询
	mylb := lb.NewRoundRobin(endpointer)

	for {
		getUserInfoEndpoint, err := mylb.Endpoint()

		ctx := context.Background()
		resp, err := getUserInfoEndpoint(ctx, service.UserRequest{
			Uid: 101,
		})
		if err != nil {
			logging.Error(err)
			os.Exit(1)
		}
		userInfo := resp.(service.UserResponse)
		logging.Info(userInfo)

		time.Sleep(time.Second * 3)

	}

}

func main1() {
	// 直连
	URL, err := url.Parse("http://127.0.0.1:8080")
	if err != nil {
		return
	}
	client := httptransport.NewClient("GET", URL, service.GetUserInfoRequestEncode, service.GetUserInfoResponseDecode)
	getUserInfoEndpoint := client.Endpoint()

	ctx := context.Background()
	resp, err := getUserInfoEndpoint(ctx, service.UserRequest{
		Uid: 101,
	})
	if err != nil {
		logging.Error(err)
		os.Exit(1)
	}
	userInfo := resp.(service.UserResponse)
	logging.Info(userInfo)
}
